let o1;
let o2;
const s='<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>' +
            '<span id="inputGroupEStatus" class="sr-only">(success)</span>';
const w='<span class="glyphicon glyphicon-warning-sign form-control-feedback" aria-hidden="true"></span>' +
            '<span id="inputGroupEStatus" class="sr-only">(warning)</span>';
function c_email(tag){
    const re_obj = /^[1-9][0-9]{4,10}@qq\.com$/;
    if (re_obj.test(tag)){
        $('#e').attr({class:"form-group has-success has-feedback"}).append(s);
        return true;
    }else{
        $('#e').attr({class:"form-group has-warning has-feedback"}).append(w);
        const l = '<p style="padding-top: 0;margin-top: 0">邮箱格式输入错误！</p>';
        $('#eStatus').html(l);
        return false;
    }
}
function c_password(tag){
    const re_obj = /^(?=.*[a-z])(?=.*\d)[^]{8,16}$/;
    if (re_obj.test(tag)){
        $('#p').attr({class:"form-group has-success has-feedback"}).append(s);
        return true;
    }else{
        $('#p').attr({class:"form-group has-warning has-feedback"}).append(w);
        const l = '<p style="padding-top: 0;margin-top: 0">密码必须包含数字,字母,且不少于8位</p>';
        $('#pStatus').html(l);
        return false;
    }
}

function closeFn (){
    // 重置input-file中的文件，使得当再次上传同一文件时，onchange也同样响应
    var file = $('#file');
    file.after(file.clone().val(""));
    file.remove();
	$('.popup-wrap').removeClass('on');
	$('#imageId').cropper("destroy");
}

// 初始化
function initCropper (){
	$('#imageId').cropper({
		viewMode: 1,
		dragMode: 'none',
		initialAspectRatio: 1,
		preview: '.previewBox',
		// 是否在容器上显示网格背景
		background: true,
		// 定义自动剪裁区域的大小
		// autoCropArea: 1,
		// 是否允许鼠标 缩放图片
		zoomOnWheel: false,
		// 是否允许改变剪裁框的大小
		cropBoxResizable:false,
		// 是否可以移动裁剪框
		cropBoxMovable:true,
		// 是否允许旋转图片
		rotatable: true,
		aspectRatio:1
		// 初始化时，自动裁剪图片
		// autoCrop:true,
	})
}
    // 角度
	let deg = 0;

	// 旋转
	function rotateFn (type){
		if(type ===1){
			deg += 90
		} else {
			deg -= 90
		}

		$('#imageId').cropper("rotate", deg);
	}

	//图像上传
	function selectImg(file) {
		if (!file.files || !file.files[0]){
				return;
		}
		var reader = new FileReader();
		reader.onload = function (evt) {
				var replaceSrc = evt.target.result;

				//更换cropper的图片
				$('#imageId').cropper('replace', replaceSrc,false);//默认false，适应高度，不失真
		}
		reader.readAsDataURL(file.files[0]);
	}
$(document).ready(function (){
    $('#InputFile').click(function (){
        initCropper();
		$('.popup-wrap').addClass('on');
    })
    $('#closeBtn').on('click',function(){
	    closeFn();
    })

	//向左旋转
	$("#btnLeft").click(function (){
        rotateFn(1);
    })
	//向右旋转
	$("#btnRight").click(function (){
        rotateFn(2);
    })

	//换向
	var flagX = true;
	$("#btnScale").on("click",function () {
		if(flagX){
			$('#imageId').cropper("scaleX", -1);
			flagX = false;
		}else{
			$('#imageId').cropper("scaleX", 1);
			flagX = true;
		}
		flagX != flagX;
	});

	//复位
	$("#btnInit").on("click",function () {
		$('#imageId').cropper("reset");
	});


	// 放大
	$("#btnLarge").on("click",function () {
		$('#imageId').cropper("zoom",0.1);
	});

	// 缩小
	$("#btnSmall").on("click",function () {
		$('#imageId').cropper("zoom",-0.1);
	});
    // 裁剪后的处理
    let base64url = '';
    $("#btnSubmit").on("click",function () {
			if (!Boolean($("#imageId").attr("src"))){
				return false;
			}else{
					var cas = $('#imageId').cropper('getCroppedCanvas');//获取被裁剪后的canvas
					base64url = cas.toDataURL('image/png'); //转换为base64地址形式
				$('#imgBoxId').attr('src',base64url);
				closeFn();
			}
	});
    $("form").click(function (){
        $('span:not(.Status)', 'form').each(function(){
            $(this).remove();
        });
        const out1=c_email(document.getElementById('InputEmail').value);
        const out2=c_password(document.getElementById('InputPassword').value);
        if (out1){
            $('#eStatus').empty();
        }
        if (out2){
            $('#pStatus').empty();
        }
        o1 = out1;
        o2 = out2;
        if ($('#InputPassword').val().length !== 0){
            if ($("#InputPassword").val() !== $('#CheckPassword').val()){
                $('#pc').attr({class:"form-group has-warning has-feedback"}).append(w);
                const s = '<p style="padding-top: 0;margin-top: 0">两次密码输入不一致！</p>';
                $('#pcStatus').html(s);
            }else{
                $('#pc').attr({class:"form-group has-warning has-feedback"}).append(s);
                $('#pcStatus').empty();
            }
        }else{
            $('#pcStatus').empty();
        }
    })
    $('#getCode').click(function (){
        if (o1 && o2){
            const address = $('#InputEmail').val();
            $.ajax({
            url: "/account/register/getCode/",
            type: "GET",
            data: {'addr':address},
            dataType: 'json',
            contentType:'application/json;charset=UTF-8',
            success: function(resp) {
                if (JSON.parse(resp.status)){
                    alert('验证码获取成功！');
                }else{
                    alert(resp.error);
                }
            },
            error: function() { alert("请求错误") },
            });
        }else{
            alert('请输入完整的邮箱地址和密码');
        }
        })

    $('#sign_up').click(function (){
        if ($('#CheckCode').val().length !==0 && o1 && o2){
            var formData = new FormData();
            formData.append('tag_in',$('#InputEmail').val());
            formData.append('pwd',$('#InputPassword').val());
            formData.append('code_in',$('#CheckCode').val());
            formData.append('csrfmiddlewaretoken',$('input[name="csrfmiddlewaretoken"]').val());
            formData.append('img',base64url);
            $.ajax({
                url:'/account/addUser/',
                type:'POST',
                cache:false,
                data:formData,
                dataType: 'json',
                processData:false,
                contentType: false,
                success:function (resp){
                    if (JSON.parse(resp.status)){
                        alert('注册成功！');
                    }else{
                        alert(resp.error);
                    }
                    location.replace('/account/login/');
                },
                error:function (){
                    alert('注册失败！');
                }
            })
        }else{
            alert('信息未完整填写！');
        }
    })

    $("#sign_in").click(function (){
        $("#form2").submit();
    })
    const signInBtn = document.getElementById("signIn");
    const signUpBtn = document.getElementById("signUp");
    const fistForm = document.getElementById("form1");
    const secondForm = document.getElementById("form2");
    const container = document.querySelector(".container");

    signInBtn.addEventListener("click", () => {
      container.classList.remove("right-panel-active");
    });

    signUpBtn.addEventListener("click", () => {
      container.classList.add("right-panel-active");
    });

    fistForm.addEventListener("submit", (e) => e.preventDefault());
    secondForm.addEventListener("submit", (e) => e.preventDefault());
})